package cn.turboinfo.fuyang.api.domain.admin.usecase.audit;

import cn.turboinfo.fuyang.api.domain.common.service.audit.CreditRatingAuditRecordService;
import cn.turboinfo.fuyang.api.domain.common.service.credit.CreditRatingService;
import cn.turboinfo.fuyang.api.domain.common.service.user.SysUserService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.enumeration.audit.AuditStatus;
import cn.turboinfo.fuyang.api.entity.common.enumeration.credit.CreditRatingStatus;
import cn.turboinfo.fuyang.api.entity.common.pojo.audit.CreditRatingAuditRecordCreator;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;

/**
 * @author gadzs
 * 评价审核usecase
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class CreditRatingReviewedUseCase extends AbstractUseCase<CreditRatingReviewedUseCase.InputData, CreditRatingReviewedUseCase.OutputData> {
    private final CreditRatingService creditRatingService;

    private final SysUserService sysUserService;

    private final CreditRatingAuditRecordService creditRatingAuditRecordService;

    @Override
    protected OutputData doAction(InputData inputData) {
        Long id = inputData.getId();
        val auditorId = inputData.getUserId();
        val creditRating = creditRatingService.getByIdEnsure(id);
        if (creditRating.getStatus() != CreditRatingStatus.PENDING) {
            throw new RuntimeException("数据状态不是待审核，操作失败");
        }

        // 更新状态
        creditRatingService.updateStatus(id, CreditRatingStatus.REVIEWED);

        val auditorUser = sysUserService.getByIdEnsure(auditorId);

        // 更新审核记录
        CreditRatingAuditRecordCreator creditRatingAuditRecord = CreditRatingAuditRecordCreator.builder()
                .withCreditRatingId(id)
                .withObjectType(creditRating.getObjectType())
                .withObjectId(creditRating.getObjectId())
                .withAuditStatus(AuditStatus.REVIEWED)
                .withUserId(auditorId)
                .withUserName(auditorUser.getUsername())
                .withRemark("审核通过")
                .build();
        creditRatingAuditRecordService.save(creditRatingAuditRecord);


        return OutputData.builder()
                .id(creditRating.getId())
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        @NotNull(
                message = "id不能为空"
        )
        private Long id;

        @NotNull(message = "审核用户ID不能为空")
        private Long userId;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private Long id;
    }

}
